<?php

if (!defined('BASEPATH'))
exit('No direct script access allowed');

class News extends MY_Controller {

	function __construct() {
		parent::__construct();
		$this->load->helper('url');
		$this->load->helper('util');
		$this->load->helper('html');
		$this->load->library('parser');
		//$this->template->set_template('home');
		//$this->template->add_region('new_tours');
		$this->load->model('news_model', 'news', true);
		$this->load->model('tour_files_model', 'file', true);
		$this->load->model('ncategory_model', 'category', true);
		$this->load->model('comment_model', 'comment', true);
		//$this->load->helper('form');
		//$this->builFrontTopMenu();
		/*
		$shortlink = trim($this->uri->segment(1));
		$cat = $this->category->getByLinkRewrite($shortlink);
		//echo trim($this->uri->segment(1));
		//print_r($cat);
		$data['category'] = $this->category->getAll(20, 0, $cat->id_ncategory, 1);
		foreach($data['category'] as $item){
			$item->url = site_url($shortlink.'/'. $item->link_rewrite);
		}

		$data['cname'] = $cat->vi_name;
		
		$data['site_url'] = site_url();
		$this->template->parse_view('left_menu', 'default/front_end/news/news_menu', $data);
		*/
		
	}

	function index($cid = -1, $offset = 0, $limit = NUMBER_RECORD_PER_PRODUCT_PAGE) {
		$this->view($cid, $offset, $limit);
	}
	
	function addComment(){
		 $result['error'] = false;
		 //$this->load->model('comment_model', 'comment', true);
		 $result['para'] = implode('---', $_POST);
		 
		 if(!empty($_POST['content']) && !empty($_POST['fullname']) &&
		  (!empty($_POST['address']) || !empty($_POST['email']) || !empty($_POST['phone']))){
		 	$id = $this->comment->insert($_POST);
		 	$result['para'] = 'Insert successful.';
		 }
		 else 
		 	$result['para'] = 'Du lieu khong hop le.';
		 
		 echo json_encode($result);
	}
	
function buildLocation($location = '', $location2 = '', $location3 = ''){

	$shortlink = trim($location); //trim($this->uri->segment(1));
	if(!empty($shortlink)){
		$cat = $this->category->getByLinkRewrite($shortlink);
		//echo trim($this->uri->segment(1));
		//print_r($cat);
		$data['category'] = $this->category->getAll(20, 0, $cat->id_ncategory, 1);
		foreach($data['category'] as $item){
			$item->url = site_url($shortlink.'/'. $item->link_rewrite);
		}

		$data['cname'] = $cat->vi_name;
	
		$data['site_url'] = site_url();
		$this->template->parse_view('left_menu', 'default/front_end/news/news_menu', $data);
	}
}

	function detail_news() { // for not category:
		$this->load->model('news_tags_model', 'news_tags', true);
        $this->load->model('tags_model', 'tags', true);
		$friendly_url = $this->uri->segment(1) ;
		$data = array();
		$data = $this->news->getByFriendlyUrl2($friendly_url);
		
		if (empty($data)){
			$this->buildFrontEndTopMenu();
			
			$data['parent_cname'] = 'Trang chủ';
			$data['child_cname'] = '';
			$this->template->parse_view('content', 'default/front_end/news/view_news_not_found', $data);
			
			$this->template->render();
			return;
		}
		
		//$data['images'] =  $this->file->getFileByTourId($id, 1);
		//$data['videos'] =  $this->file->getFileByTourId($id, 2);
		//print_r($data);
		//$data['tour'] = $tour;
		$data['base_url'] = base_url();
		//$data['image_path'] = base_url() . TOUR_IMAGE_PATH;
		$track = getTrackNews($data['id_ncategory']);
		
		$data['child_cname'] = '';
		$parent_link_rewrite = '';
		$current_link_rewrite = '';
		if (!empty($track)){
			$parent = $track[0];
			$parent_link_rewrite = $parent->link_rewrite;
			$data['parent_cname'] = $parent->name;
			if (isset($track[1])){
				$data['child_cname'] = $track[1]->name;
				$current_link_rewrite = $track[1]->link_rewrite;
			}
		}
		
		$this->buildFrontEndTopMenu($parent_link_rewrite, $current_link_rewrite);
		
		//print_r($track ); 
		
		$data['comments'] = $this->comment->getAllNewsId($data['id_news']);
		$data['numcomment'] = count($data['comments']);
		$a = 0;
		foreach ($data['comments'] as &$item){
			$item['class'] = $a % 2 == 0 ? 'odd' : '';
			$a++;
		}
		//print_r($data['comments']);
		
		$data['other_news'] = $this->news->getNewsOther($data['id_news'], $data['id_ncategory']);
		foreach ($data['other_news'] as &$item){
			$item['link'] = site_url($item['friendly_url']);
			$item['oname'] = $item['vi_name'];
			$item['osummary'] = $item['vi_summary'];
			$item['odate_add'] = $item['date_add'];
		}
		//print_r($data['other_news']);
		
		$tags_arr = $this->news_tags->getTagsByNewsID($data['id_news']);
        
        $tags_name = array();
        
        $tags = array();
        
    	for($i = 0; $i < count($tags_arr); $i++){
    		$tags[] =  anchor('tag/' . trim($tags_arr[$i]['tag_name']) , ' ' . trim($tags_arr[$i]['tag_name']), 'title="'.trim($tags_arr[$i]['tag_name']).'"');
    	}
    	
    	$data['tags'] = implode(',', $tags);
    	$data['share_facebook'] = 'http://facebook.com/share.php?u=' . site_url($friendly_url);
    	$data['share_google'] = 'https://www.google.com.vn/bookmarks/mark?op=add&bkmk='.site_url($friendly_url).'&title='.$data['vi_name'].'&annotation=123456';
		
    	$this->template->write('page_title',  $data['vi_name']);
    	$this->template->write('page_description',  $data['vi_summary']);
    	
    	$this->template->parse_view('content', 'default/front_end/news/view_news_detail', $data);
		$this->template->render();
	} 
	
	function tag($tag, $page = 0){
		$tag = rawurldecode($tag);
		$this->load->model('news_tags_model', 'news_tags', true);
        $this->load->model('tags_model', 'tags', true);
        
        $this->buildFrontEndTopMenu();
        
        $data['cname'] = 'TAG';
        
        $data['scname'] = $tag;
		
        $news = $this->news_tags->getNewsByTag($tag);
        //print_r($news);
		$data['rows'] = $news;
		$index = 0;
		$main = array();
		$other = array();
		$now = strtotime(date('y-m-d'));
		foreach ($data['rows'] as &$item){
			if($item['image'] != ""){
				$item['image'] = '<img class="fltlft thumb_news" width="100" src="'.base_url(NEWS_IMAGE_PATH.$item['image']) . '"/>';
			}
			else
			$item['image'] = '<img class="fltlft thumb_news" width="100" src="'.base_url('images/img_news.png') . '"/>';
			//$item['vi_name'] = 123 . $item['vi_name'];
			//$item['url'] = site_url($parent.'/chi-tiet/' . $item['id_news']);
			$item['url'] = site_url($item['friendly_url']);
			$item['box'] = $index == 0 ? 'box_shadow' : 'med_news_list';
			
			$date_created = strtotime($item['date_add']);
			if(($now - $date_created)/(60*60*24) <= 1){
				$item['new_icon'] = img(array('src' => base_url('images/new.gif')));
			}
			else 
				$item['new_icon'] = '';
				
			if ($index < 10){
				$main[] = $item;
			}
			else 
				$other[] = $item;
				
			$index++;
			//echo "<br> MY NAME : " . $item['vi_name'];
		}
		
		$data['main'] = $main;
		$data['other'] = $other;
        //print_r($news);
        
		//print_r($data['tours']);
		$data['image_path'] = base_url() . NEWS_IMAGE_PATH;
		
		$this->template->parse_view('content', 'default/front_end/news/view_news', $data);
		//$this->template->render();
		//}

		//$this->template->parse_view('content', 'default/front_end/home/view_home', $data);
		//$this->buildLeftContent();

		$this->template->render();
	}
	
	function content($parent = '', $catagory = '', $offset = 0, $limit = NUMBER_RECORD_PER_PRODUCT_PAGE) {
		
		$this->buildFrontEndTopMenu();
		
		//echo "Parent: $parent/ catagory:  $catagory/ offset: $offset";
		$prefix = 'p-';
		$segment = 3;
		
		$catagory = trim( $catagory);
		
		if (strpos($catagory, $prefix) !== false){
			$segment = 2;
			$catagory = '';
		}
			
		$cat = '';

		$data = array();

		//if(empty($catagory )){
		if(!empty($catagory)){
			$cat = $this->category->getByLinkRewrite(trim($catagory));
		}
		else
			$cat = $this->category->getByLinkRewrite($parent);
		//echo $cat->vi_nama;
		$parent_id = -1;

		if($cat)
			$parent_id = $cat->id_ncategory;
		else{
			redirect('home');
			return;
		}

		$subcats = $this->category->getAll(20, 0, $parent_id);

		$arrCats = array($parent_id);

		for($a = 0; $a < count($subcats); $a++){
			$arrCats[] = $subcats[$a]->id_ncategory;
			$sitem = $subcats[$a];
		}
		
		$offset = explode('p-', $offset);
		//print_r($offset);
		//echo "offset:" .  $offset = $offset[1];
		//echo "<br>intval:" . ((int)("abc2012")) . "<br>";
		
		$tmp = $this->uri->segment($segment);
			if (!empty($tmp)){
				$tmp = explode($prefix, $tmp);
				$offset = $tmp[1];
			}
			else 
				$offset = 0;	
				
		$news = array();
		if(count($arrCats) > 0)
		$news = $this->news->getAllByCategoryIds($arrCats, 20, $offset);
		$now = strtotime(date('y-m-d'));
		$data['rows'] = $news;
		$index = 0;
		$main = array();
		$other = array();
		foreach ($data['rows'] as &$item){
			
			if($item['image'] != ""){
				$item['image'] = '<img class="fltlft thumb_news" width="100" src="'.base_url(NEWS_IMAGE_PATH.$item['image']) . '"/>';
			}
			else
			$item['image'] = '<img class="fltlft thumb_news" width="100" src="'.base_url('images/img_news.png') . '"/>';
			//$item['vi_name'] = 123 . $item['vi_name'];
			//$item['url'] = site_url($parent.'/chi-tiet/' . $item['id_news']);
			$item['url'] = site_url($item['friendly_url']);
			$item['box'] = $index == 0 ? 'box_shadow' : 'med_news_list';
			
			$date_created = strtotime($item['date_add']);
			if(($now - $date_created)/(60*60*24) <= 1){
				$item['new_icon'] = img(array('src' => base_url('images/new.gif')));
			}
			else 
				$item['new_icon'] = '';
				$main[] = $item;
			/*if ($index < 10){
				$main[] = $item;
			}
			else 
				$other[] = $item;
				*/
			$index++;
			//echo "<br> MY NAME : " . $item['vi_name'];
		}
		
		$data['main'] = $main;
		$data['other'] = $other;
		
		$shortlink = trim($this->uri->segment(1));
		$cat = $this->category->getByLinkRewrite($shortlink);
		//echo trim($this->uri->segment(1));
		//print_r($cat);
		$data['category'] = $this->category->getAll(20, 0, $cat->id_ncategory, 1);
		foreach($data['category'] as &$item){
			$item->url = site_url($shortlink.'/'. $item->link_rewrite);
		}
		$data['cname'] = $cat->vi_name;
		
		$link_rewrite = $this->uri->segment(2);
		if(!empty($link_rewrite)){
		$scat = $this->category->getByLinkRewrite($this->uri->segment(2));
		$scname = ":.";
		if($scat){
			$scname .= $scat->vi_name;
		}
		$data['scname'] = $scname;
		}
		else 
			$data['scname'] = '';
		
		//print_r($data['tours']);
		$data['image_path'] = base_url() . NEWS_IMAGE_PATH;
		
		$page = $offset; //(int) $this->uri->segment(5);
        $config['base_url'] = site_url($parent . '/' . $catagory);
		//echo 'Selemt :' . $this->uri->segment(3);
        $config['total_rows'] = $this->news->countAllByCategoryIds($arrCats);
        $config['per_page'] = 20; //NUMBER_RECORD_PER_PAGE;
        $config['uri_segment'] = $segment;
        $config['next_tag_open'] = '<li>';
        $config['next_tag_close'] = '</li>';
        $config['prev_tag_open'] = '<li>';
        $config['prev_tag_close'] = '</li>';
        $config['num_tag_open'] = '<li>';
        $config['num_tag_close'] = '</li>';
        $config['first_tag_open'] = '<li>';
        $config['first_tag_close'] = '</li>';
        $config['last_tag_open'] = '<li>';
        $config['last_tag_close'] = '</li>';
        $config['next_link'] = 'Sau';
        $config['prev_link'] = 'Trước';
        $config['first_link'] = 'Trang đầu';
        $config['last_link'] = 'Trang cuối';
        $config['cur_tag_open'] = '<li class="current">';
        $config['cur_tag_close'] = '</li>';
        $config['prefix'] = $prefix;
        $config['num_links'] = 5;
        
		$this->load->library('pagination');
        $this->pagination->initialize($config);
		
		$this->template->parse_view('content', 'default/front_end/news/view_news', $data);
		//$this->template->render();
		//}

		//$this->template->parse_view('content', 'default/front_end/home/view_home', $data);
		//$this->buildLeftContent();

		$this->template->render();

	}

	function content2($parent = '', $catagory = '', $offset = 0, $limit = NUMBER_RECORD_PER_PRODUCT_PAGE) {
		$catagory = trim( $catagory);
		$cat = '';

		$data = array();

		if(empty($catagory )){
			$cat = $this->category->getByLinkRewrite($parent);
			//echo $cat->vi_nama;
			$parent_id = -1;

			if($cat)
			$parent_id = $cat->id_ncategory;
			else{
				redirect('home');
				return;
			}

			$data['categories'] = $this->category->getAll(20, 0, $parent_id);
			// print_r($data['categories']);
			$index = 0;
			foreach ($data['categories'] as &$item) {
				$news = $this->news->getAll(0, 4, $item->id_ncategory, 1);
				if(count($news) > 0){
					$main_data = $news[0];
					$main_data['image'] = $main_data['image'] != '' ? '<div class="image">
            <a href="#"><img src="'. base_url(NEWS_IMAGE_PATH. $main_data['image']). '"></a>
        </div>' : '<div class="image">
            <a href="#"><img src="'. base_url('images/gold_cash.png'). '"></a>
        </div>';
					$main_data['url'] = site_url($parent.'/chi-tiet/' . $main_data['id_news']);
					$item->main_news = $this->parser->parse('default/front_end/home/main_news', $main_data, true);

					if(count($news) >= 1){
						$other_news = array();
						for($i = 1; $i < count($news) ; $i++){
							$other = $news[$i];
							$other['url'] = site_url($parent.'/chi-tiet/' . $other['id_news']);
							$other_news[] = $other;
						}

						//echo 'other: ' . count($other_news);
						if(count($other_news) > 0)
						$item->other_news = $this->parser->parse('default/front_end/home/home_other_news', array('news' => $other_news ), true);
						else
						$item->other_news = '';
					}
				}
				else{
					unset($data['categories'][$index]);
					//$item/->main_news = $this->parser->parse('default/front_end/home/main_news', $data, true);
					//$item->other_news = $this->parser->parse('default/front_end/home/home_other_news', $data, true);
				}
				$index++;
			}

			$this->template->parse_view('content', 'default/front_end/home/view_home', $data);
		}
		else{
			$cat = $this->category->getByLinkRewrite(trim($this->uri->segment(2)));
			//$news = $this->news->getAll($offset, $limit, $cat->id_ncategory, 1);
			$news = $this->news->getAll(0, 20, $cat->id_ncategory, 1);

			$data['news'] = $news;
			foreach ($data['news'] as &$news){
				if($news['image'] != '' || $news['image'] != null)
				$news['image'] = '<img src="'.base_url(). NEWS_IMAGE_PATH .$news['image'].'" width="100" height="80" align="left" />';
				else
				$news['image'] = '';
					
				$news['detail_link'] = site_url(trim($this->uri->segment(1)). '/chi-tiet/' . $news['id_news']);


			}

			//print_r($data['news']);

			//print_r($data['tours']);
			$data['image_path'] = base_url() . NEWS_IMAGE_PATH;
			$this->template->parse_view('content', 'default/front_end/news/view_news', $data);
			//$this->template->render();
		}


		//$this->template->parse_view('content', 'default/front_end/home/view_home', $data);
		//$this->buildLeftContent();

		$this->template->render();

	}



	function view($cid = -1, $offset = 0, $limit = NUMBER_RECORD_PER_PRODUCT_PAGE) {
		$news = $this->news->getAll($offset, $limit, $cid, 1);

		$data['news'] = $news;
		foreach ($data['news'] as &$news){
			if($news['image'] != '' || $news['image'] != null)
			$news['image'] = '<img src="'.base_url(). NEWS_IMAGE_PATH .$news['image'].'" width="100" height="80" align="left" />';
			else
			$news['image'] = '';

			$news['detail_link'] = site_url('news/detail/' . $news['id_news']);


		}

		//print_r($data['news']);

		//print_r($data['tours']);
		$data['image_path'] = base_url() . NEWS_IMAGE_PATH;
		$this->template->parse_view('content', 'default/front_end/news/view_news', $data);
		$this->template->render();
	}

	function detail($cat, $id) {
		//echo $cat;
		$data = array();
		$data = $this->news->getById($id);
		//$data['images'] =  $this->file->getFileByTourId($id, 1);
		//$data['videos'] =  $this->file->getFileByTourId($id, 2);
		//print_r($data);
		//$data['tour'] = $tour;
		$data['base_url'] = base_url();
		//$data['image_path'] = base_url() . TOUR_IMAGE_PATH;
		$this->template->parse_view('content', 'default/front_end/news/view_news_detail', $data);
		$this->template->render();
	}

	function detail_old($id) {
		$data = array();
		$data = $this->news->getById($id);
		//$data['images'] =  $this->file->getFileByTourId($id, 1);
		//$data['videos'] =  $this->file->getFileByTourId($id, 2);
		//print_r($tour);
		//$data['tour'] = $tour;
		$data['base_url'] = base_url();
		//$data['image_path'] = base_url() . TOUR_IMAGE_PATH;
		$this->template->parse_view('content', 'default/front_end/news/view_news_detail', $data);
		$this->template->render();
	}


	function buildLeftContent() {
		$data['menuitems'] = array(
		array(
                'status' => 'active',
                'click_function' => 'get_list(current_from, this);',
                'text' => 'Add New Child',
                'href' => site_url('children/add_child'),
                'subitem' => array('a' => 'a')
		),
		array(
                'status' => '',
                'click_function' => 'create_user(this);',
                'text' => 'View All Children ',
                'href' => site_url('children/view_all'),
                'subitem' => array('a' => 'a')
		),
		array(
                'status' => '',
                'click_function' => 'system_logs(this);',
                'text' => 'View Current Children ',
                'href' => site_url('children/view_current'),
                'subitem' => array('a' => 'a')
		),
		array(
                'status' => '',
                'click_function' => 'login_logs(this);',
                'text' => 'View Graduated Children ',
                'href' => site_url('children/view_graduated'),
                'subitem' => array('a' => 'a')
		),
		array(
                'status' => '',
                'click_function' => 'system_config(this);',
                'text' => 'View Withdrawn Children ',
                'href' => site_url('children/view_withdraw'),
                'subitem' => array('a' => 'a')
		)
		);
		//$this->load->library('parser');
		$this->parser->parse('default/front_end/menu_left', $data);
		$this->template->parse_view('header', 'default/front_end/menu_left', $data);
	}

}

?>